<template>
  <div class="main">
    <p  class="main_text">
      分账记录
    </p>
    <div class="cyr-flex">
      <el-tabs v-model="activeName" @tab-change="handleTabChange">
        <el-tab-pane name="personal">
          <template #label>
            <span>个人</span>
          </template>
          <!-- ############################################## 查询 ############################################## -->
          <div class="top  ">
            <el-form :model="searchFormModel" ref="personalFormRef" inline>
              <el-form-item label="操作时间" prop="beginTime">
                <FormDate v-model:startTime="searchFormModel.beginTime" v-model:endTime="searchFormModel.endTime"
                  v-model:radio="personalRadio">
                  <span style="margin:0 10px">至</span>
                </FormDate>
              </el-form-item>
<!--              <el-form-item label="用户名" prop="name">-->
<!--                <el-input v-model="searchFormModel.name" style="width: 200px" />-->
<!--              </el-form-item>-->
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="searchFormModel.phone" style="width: 200px" />
              </el-form-item>
              <el-form-item label="订单号" prop="orderSn">
                <el-input v-model="searchFormModel.orderSn" style="width: 200px" />
              </el-form-item>
              <el-form-item label="入账类型" prop="type">
                <el-select v-model="searchFormModel.type" style="width: 200px">
                  <el-option label="入账" value="入账" />
                  <el-option label="提现" value="提现" />
                </el-select>
              </el-form-item>
              <el-form-item label="分账类型" prop="originType">
                <el-select v-model="searchFormModel.originType" style="width: 200px">
                  <el-option label="直推" value="1" />
                  <el-option label="间推" value="2" />
                  <el-option label="团队" value="3" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handlePersonal">查询</el-button>
                <el-button type="primary" plain @click="handlePformReset(personalFormRef)">重置</el-button>
              </el-form-item>
            </el-form>
            <el-divider />
            <div style="text-align: right">
              <el-button type="primary" style="padding:0 25px;margin-bottom: 10px;"  @click="handleExportExcelPersonal">导出明细</el-button>
            <el-button type="primary" style="padding:0 25px;margin-bottom: 10px;" @click="openFileDialog">导入</el-button>
            </div>
          </div>
          <el-table :data="personalTableData"
            :header-cell-style="{ background: '#f0f6fe' }" :show-overflow-tooltip="true"  border>
            <el-table-column label="编号" type="index" width="80" />
            <el-table-column label="用户名" prop="username" width="80" />
            <el-table-column label="手机号" prop="userPhone" width="120" />
            <!--            <el-table-column-->
            <!--              label="银行卡号"-->
            <!--              prop="userCard"-->
            <!--              width="100"-->
            <!--              >-->
            <!--              <template #default="props">-->
            <!--    {{props.row.userCard.bandCardNo}}-->
            <!--              </template>-->
            <!--          </el-table-column>-->
            <!--            <el-table-column-->
            <!--              label="卡主姓名"-->
            <!--              prop="realName"-->
            <!--               />-->
            <el-table-column label="订单号" prop="orderSn" />
<!--            <el-table-column label="订单来源" prop="origin">-->
<!--              <template #default="props">-->
<!--                {{ props.row.orderSn === 's' ? '商城' : '收车' }}-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column label="分账金额" prop="amount" />
            <el-table-column label="分账类型" :formatter="originFormatter">
<!--              <template #default="props">-->
<!--                {{ getoriginType(props.row.originType) }}-->
<!--              </template>-->
            </el-table-column>
            <el-table-column label="入账类型" prop="created">
              <template #default="props">
                {{ props.row.type === '提现' ? '出账' : props.row.type }}
              </template>
            </el-table-column>
            <el-table-column label="来源" >
              <template #default="props">
                {{ props.row.origin === 't' ? '拖车':(props.row.origin==='s'?'商城':'团队奖入账') }}
              </template>
            </el-table-column>

            <el-table-column label="创建时间" prop="createdAt" />
<!--            <el-table-column label="更新时间" prop="updatedAt" />-->
          </el-table>
          <!-- 分页 -->
          <smartPager v-model:current-page="personalCurrentPage" v-model:page-size="personalPageSize"
            :total="personalTableTotal" @change="handlePersonalCurrentChange" />

        </el-tab-pane>
        <el-tab-pane name="company">
          <template #label>
            <span>公司</span>
          </template>
          <!-- ############################################## 查询 ############################################## -->
          <div class="top">
            <el-form :model="companySearchFormModel" ref="companyFormRef" inline>
              <el-form-item label="操作时间" prop="startAt">
                <FormDate v-model:startTime="companySearchFormModel.startAt"
                  v-model:endTime="companySearchFormModel.endAt" v-model:radio="companyRadio">
                  <span style="margin:0 10px">至</span>
                </FormDate>
              </el-form-item>
              <el-form-item label="订单号" prop="orderSn">
                <el-input v-model="companySearchFormModel.orderSn" style="width: 200px" />
              </el-form-item>
              <el-form-item label="拆解厂/公司名称" prop="orderId">
                <el-input v-model="companySearchFormModel.companyName" style="width: 200px" />
              </el-form-item>
              <el-form-item label="发票状态(易宝手续费)" prop="commissionInvoiceStatus">
                <el-select v-model="companySearchFormModel.commissionInvoiceStatus" style="width: 200px">
                  <el-option label="未开票" :value="false" />
                  <el-option label="已开票" :value="true" />
                </el-select>
              </el-form-item>
              <el-form-item label="发票状态(平台)" prop="invoiceStatus">
                <el-select v-model="companySearchFormModel.invoiceStatus" style="width: 200px">
                  <el-option label="未开票" :value="false" />
                  <el-option label="已开票" :value="true" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleCompany">查询</el-button>
                <el-button type="primary" plain @click="handleCformReset(companyFormRef)">重置</el-button>
              </el-form-item>
            </el-form>
            <el-divider />
            <div style="text-align: right">
              <el-button type="primary" style="padding:0 25px;margin-bottom: 10px;" @click="handleExportExcelCompany">导出明细</el-button>
            </div>
          </div>
          <el-table :data="companyTableData"
            :header-cell-style="{ background: '#f0f6fe' }"  :show-overflow-tooltip="true"  border>
            <el-table-column label="编号" type="index" width="80" />
            <el-table-column label="订单号" prop="orderSn" />
            <el-table-column label="公司名称" prop="companyName" />
            <el-table-column label="总支出" prop="totalFee" />
            <el-table-column label="拖车费用" prop="residualFee" />
            <el-table-column label="服务费" prop="serviceFee" />
            <el-table-column label="手续费" prop="commission" />
            <el-table-column label="发票状态(易宝手续费)" prop="commissionInvoiceStatus">
              <template #default="props">
                {{ props.row.commissionInvoiceStatus == false ? '未开票' : '已开票' }}
              </template>
            </el-table-column>
            <el-table-column label="发票状态(平台)" prop="invoiceStatus">
              <template #default="props">
                {{ props.row.invoiceStatus == false ? '未开票' : '已开票' }}
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createdAt" />
            <el-table-column label="更新时间" prop="updatedAt" />
          </el-table>

          <!-- 分页 -->
          <smartPager v-model:current-page="companyCurrentPage" v-model:page-size="companyPersonalPageSize"
          :total="companyTableTotal" @change="handleCompanyCurrentChange" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
  <el-dialog
      v-model="dialogVisible"
      title="导入"
      align-center
      :show-close="false"
      width="600"
  >
<UploadFile @file-change="handleFileChange" />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitFile">
          保存
        </el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import FormDate from '@/components/CyrForm/FormDate.vue';
import { formatJson, formatTimeHan } from '@/utils';
import { exportJson2Excel } from '@/utils/excel';
import {
  RequestPersonalRecords,
  RequestCompanyRecords,
  RequestUploadExcelTemp
} from "@/api/path/index.js";
import UploadFile from './components/UploadFile.vue'

/*************************************公共*****************************************/
const activeName = ref<string>('personal')
//查询表单

//分账类型处理
function initOriginType(val:number){
  switch (val) {
    case 1:
      return '直推'
    case 2:
      return '间推'
    case 3:
      return '团队'
    case 4:
      return '团队奖'
    default:
      break
  }
}
const originFormatter=(row: any)=>{
  return initOriginType(row.originType)
}

const handleTabChange = (TabPaneName: string | number) => {
  try {
    if (TabPaneName === 'personal') {
      personalData(searchFormModel.value)
    } else {
      companyData(companySearchFormModel.value)
    }
  } catch (e) {
    console.log(e)
  } finally {
    console.log(TabPaneName)
  }
}
/*************************************个人*****************************************/
//个人表单
const personalPage = ref(1)
const personalFormRef = ref<FormInstance>()
const searchFormModel = ref({
  beginTime: '',
  endTime: '',
  name: '',
  phone:'',
  orderSn: '',
  type: '',
  originType: '',
  page: personalPage.value,
  rows: 10
})
const personalRadio = ref<string>()
const personalCurrentPage = ref(1)
const personalPageSize = ref(10)
//个人Data
const personalTableData = ref<any[]>([])
const personalTableTotal = ref<number>(0)
/* 查询个人-公司 */
const handlePersonal = () => {
  handleTabChange(activeName.value)
}
/* 重置个人*/
const handlePformReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  searchFormModel.value.endTime = ''
  personalRadio.value = ''
  searchFormModel.value.page = 1
  personalCurrentPage.value = 1
  personalData(searchFormModel.value)
}
function personalData(personalValue: any) {
  searchFormModel.value.page = personalCurrentPage.value
  searchFormModel.value.rows = personalPageSize.value
  RequestPersonalRecords(personalValue).then((res: any) => {
    personalTableData.value = res.resultObj.data
    personalTableTotal.value = res.resultObj.total
  })
}
function handlePersonalCurrentChange(val: number) {
  searchFormModel.value.page = val
  handleTabChange(activeName.value)
}
/*************************************公司*****************************************/
//公司表单
const companyFormRef = ref<FormInstance>()
const companyPage = ref(1)
const companySearchFormModel = ref({
  startAt: "",
  endAt: "",
  orderSn: '',
  companyName: '',
  commissionInvoiceStatus: '',
  invoiceStatus: '',
  page: companyPage.value,
  rows: 10
})
const companyRadio = ref<string>()
//公司Data
const companyTableData = ref<any[]>([])
const companyTableTotal = ref<number>(0)
const companyCurrentPage = ref(1)
const companyPersonalPageSize = ref(10)
/* 查询公司 */
const handleCompany = () => {
  handleTabChange(activeName.value)
}
/* 重置公司*/
const handleCformReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  companySearchFormModel.value.endAt = ''
  companyRadio.value = ''
  companySearchFormModel.value.page = 1
  companyCurrentPage.value = 1
  companyData(companySearchFormModel.value)
};

function companyData(companyValue: any) {
  companySearchFormModel.value.page = companyCurrentPage.value
  companySearchFormModel.value.rows = companyPersonalPageSize.value
  RequestCompanyRecords(companyValue).then((res: any) => {
    companyTableData.value = res.resultObj.data
    companyTableTotal.value = res.resultObj.total
  })
}
function handleCompanyCurrentChange(val: number) {
  companySearchFormModel.value.page = val
  handleTabChange(activeName.value)
}

handleTabChange(activeName.value)
//导入excel模板弹窗
const dialogVisible=ref(false)
const openFileDialog=()=>{
  dialogVisible.value=true
}
const file=ref()
const  submitFile=()=>{
  if(!file.value){
    ElMessage.warning('请上传文件')
    return
  }
  const formData=new FormData()
  formData.append('excelFile', file.value[0])
  RequestUploadExcelTemp(formData).then((res:any)=>{
    if(res.success === true){
      ElMessage.success('上传成功')
      dialogVisible.value=false
      personalData(searchFormModel.value)
    }else{
      ElMessage.error(res.msg)
    }
  })
}
const handleFileChange=(val:File)=>{
  file.value=val
}
/**
 * 导出Excel
 */
const handleExportExcelPersonal = () => {
  const tHeader = ['编号', '用户名', '手机号', '订单号', '分账金额', '分账类型', '入账类型','来源', '创建时间']
  const filterVal = ['id', 'username', 'userPhone', 'orderSn', 'amount', 'originType', 'type','origin', 'createdAt']
  const list = personalTableData.value.map((item, index) => {
    return {
      ...item,
      id: index,
      originType:initOriginType(item.originType),
      type:item.type === '提现' ? '出账' :item.type,
      origin:item.origin === 't'? '拖车':(item.origin==='s'?'商城':'团队奖入账'),
    }
  })
  const data = formatJson(filterVal, list)
  exportJson2Excel(tHeader, data, `${formatTimeHan(new Date())}物流结算`, undefined, undefined,)
}

const handleExportExcelCompany = () => {
  const tHeader = ['编号', '订单号', '公司名称', '总支出', '拖车费用', '服务费', '手续费','发票状态(易宝)','发票状态(平台)','创建时间','更新时间']
  const filterVal = ['id', 'orderSn', 'companyName', 'totalFee', 'residualFee', 'serviceFee', 'commission','commissionInvoiceStatus','invoiceStatus','createdAt','updatedAt']
  const list = companyTableData.value.map((item, index) => {
    return {
      ...item,
      id: index,
      commissionInvoiceStatus:item.commissionInvoiceStatus? '已开票' : '未开票',
      invoiceStatus:item.invoiceStatus? '已开票' : '未开票',
    }
  })
  const data = formatJson(filterVal, list)
  exportJson2Excel(tHeader, data, `${formatTimeHan(new Date())}个人分账结算`, undefined, undefined,)
}

</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .top {
    width: 100%;
    background-color: #fff;
  }

  .content {
    width: 100%;
    background-color: #fff;
  }
}
</style>
